﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using KPIS.GERP.GIMS.BLL;
using KPIS.GERP.GIMS.IBLL;
using KPIS.GERP.GIMS.MODEL;
using System.Data;
using System.IO;

namespace KPIS.GERP.GIMS.APP.APP_UI.Add_Form
{
    public partial class ICM_Bid : System.Web.UI.Page
    {
        Common.Main cn =new  Common.Main();
        CommandControl cmdFac = new CommandControl();
        IBLLSysDurationType bllDurationType = new SysDurationTypeBLL();
        IBLLHrmEmployee bllEmployee = new HrmEmployeeBLL();
        IBLLPersonal bllPersonal = new PersonalBLL();
        IBLLMasterCommitteeFunction bllComFunction = new MasterCommitteeFunctionBLL();
        IBLLMasterCommitteePosition bllComPosition = new MasterCommitteePositionBLL();
        PurchaseRequestBLL bllPr = new PurchaseRequestBLL();
        PurchaseRequestItemBLL bllPcReqItem = new PurchaseRequestItemBLL();
        PurchaseRequestCommitteeBLL bllPrCommittee = new PurchaseRequestCommitteeBLL();
        BidBLL bllBid = new BidBLL();
        private const int ItemsPerRequest = 10;
        double totalPrice = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetBidDetail();
                LoadGridItem();
                LoadCommitteeFunction();
                LoadCommitteePosition();
                LoadGridCommittee();
                LoadGridFile();
                rdbFree.Attributes.Add("onclick", "return ChangeReceiveFree('" + panelDocAmount.ClientID + "')");
                rdbSell.Attributes.Add("onclick", "return ChangeReceiveSell('" + panelDocAmount.ClientID + "')");
                panelDocAmount.Attributes.Add("style", "visibility:hidden");
            }
        }

        protected int GetSeq()
        {
            int seq = Convert.ToInt32(Request.QueryString["Seq"]);
            return seq;
        }

        #region tab รายการพัสดุ

        protected void LoadGridItem()
        {
            int seq = GetSeq();
            IList<PurchaseRequestItemInfo> infoPcReqItem = bllPcReqItem.GetPurchaseRequestItem_EditPcReq(seq);
            Grid_Item.DataSource = infoPcReqItem;
            Grid_Item.MasterTableView.GroupByExpressions.Clear();
            GridGroupByExpression geExpense = new GridGroupByExpression(Grid_Item.Columns[0]);
            Grid_Item.MasterTableView.GroupByExpressions.Add(geExpense);
            Grid_Item.DataBind();
        }

        protected void Grid_Item_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridItem();
        }

        protected void Grid_Item_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                double qty = 0;
                double price = 0;
                GridDataItem dataBoundItem = e.Item as GridDataItem;

                if (((Label)(dataBoundItem["Qty"].FindControl("lblQty"))).Text.Length > 0)
                {
                    qty = double.Parse(((Label)(dataBoundItem["Qty"].FindControl("lblQty"))).Text);
                }
                if (((Label)(dataBoundItem["Price"].FindControl("lblPrice"))).Text.Length > 0)
                {
                    price = double.Parse(((Label)(dataBoundItem["Price"].FindControl("lblPrice"))).Text);
                }

                totalPrice += (qty * price);

                //if (!Object.Equals(target, null))
                //{
                //    if (!Object.Equals(this.TipItemDetail, null))
                //    {
                //        this.TipItemDetail.TargetControls.Add(target.ClientID, "Item:" + dataBoundItem["InfoItem.Seq"].Text, true);
                //    }
                //}
            }
            else if (e.Item is GridFooterItem)
            {
                GridFooterItem footer = (GridFooterItem)e.Item;
                footer["Descr"].Controls.Add(new LiteralControl("<div align='right' style='color: Black; font-weight: bold;'>วงเงินจัดหาทั้งหมด :</div> "));
                ((Label)footer["Price"].FindControl("lblTotalPrice")).Text = totalPrice.ToString("###,###,##0.00");
            }
        }

        protected void nextButton_Item_Click(object sender, EventArgs e)
        {
            LoadValiDateDetail();
            RadManager1.ResponseScripts.Add(@"ChangeTab('Detail',1, '');");
        }

        #endregion

        #region Tab ข้อมูลประกาศ

        protected void GetBidDetail()
        {
            int seq = GetSeq();
            PurchaseRequestInfo info = bllPr.GetPurchaseRequest(seq);
            lblYearType.Text = info.InfoYearType.Name;
            lblBgmYear.Text = info.BgmYear.ToString();
            lblPcRule.Text = info.InfoPurchaseRule.Name;
            lblPrType.Text = info.PurchaseType;
            lblPrRefNo.Text = info.Ref_No;
            lblPrName.Text = info.Name;

            txtDate.Text = String.Format("{0:dd/MM/yyyy}", DateTime.Today);
            CalendarDate.FocusedDate = DateTime.Today;
            CalendarDate.SelectedDate = DateTime.Today;
            txtName.Text = "ประกาศ" + info.PurchaseType + info.Name;

            hdYearType.Value = info.InfoYearType.Seq.ToString();
        }

        protected void backButton_Detail_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('Item',0, 'validate');");
        }

        protected void nextButton_Detail_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('Committee',2, 'validate');");
        }

        private void LoadValiDateDetail()
        {
            RequiredFieldValidator valDate = new RequiredFieldValidator();
            valDate.ID = "ValtxtDate";
            valDate.ControlToValidate = "txtDate";
            valDate.SetFocusOnError = true;
            valDate.Display = ValidatorDisplay.Dynamic;
            valDate.ErrorMessage = "* กรุณาระบุวันที่รายการ *";
            panelValtxtDate.Controls.Add(valDate);
            CustomValidator valCustomDate = new CustomValidator();
            valCustomDate.ID = "ValCustomDate";
            valCustomDate.ControlToValidate = "txtDate";
            valCustomDate.SetFocusOnError = true;
            valCustomDate.Display = ValidatorDisplay.Dynamic;
            valCustomDate.ErrorMessage = "* กรุณาระบุวันที่ให้ถูกต้อง *";
            valCustomDate.ClientValidationFunction = "validateDate";
            panelValtxtDate.Controls.Add(valCustomDate);
            RequiredFieldValidator valRefNo = new RequiredFieldValidator();
            valRefNo.ID = "ValtxtRefNo";
            valRefNo.ControlToValidate = "txtRefNo";
            valRefNo.SetFocusOnError = true;
            valRefNo.Display = ValidatorDisplay.Dynamic;
            valRefNo.ErrorMessage = "* กรุณาระบุเลขที่ประกาศ *";
            panelValtxtRefNo.Controls.Add(valRefNo);
            RequiredFieldValidator valName = new RequiredFieldValidator();
            valName.ID = "ValtxtName";
            valName.ControlToValidate = "txtName";
            valName.SetFocusOnError = true;
            valName.Display = ValidatorDisplay.Dynamic;
            valName.ErrorMessage = "* กรุณาระบุเรื่องประกาศ *";
            panelValtxtName.Controls.Add(valName);
            CustomValidator valAnnounce = new CustomValidator();
            valAnnounce.ID = "ValtxtDateAnnounce";
            valAnnounce.ControlToValidate = "txtDateAnnounce";
            valAnnounce.SetFocusOnError = true;
            valAnnounce.Display = ValidatorDisplay.Dynamic;
            valAnnounce.ErrorMessage = "* กรุณาระบุวันที่ลงนามประกาศให้ถูกต้อง *";
            valAnnounce.ClientValidationFunction = "validateDate";
            panelValAnnounce.Controls.Add(valAnnounce);
            CustomValidator valReceiveStart = new CustomValidator();
            valReceiveStart.ID = "ValtxtDateReceiveStart";
            valReceiveStart.ControlToValidate = "txtDateReceiveStart";
            valReceiveStart.SetFocusOnError = true;
            valReceiveStart.Display = ValidatorDisplay.Dynamic;
            valReceiveStart.ErrorMessage = "* กรุณาระบุวันที่เริ่มจำหน่ายเอกสารให้ถูกต้อง *";
            valReceiveStart.ClientValidationFunction = "validateDate";
            panelValReceive.Controls.Add(valReceiveStart);
            CustomValidator valReceiveEnd = new CustomValidator();
            valReceiveEnd.ID = "ValtxtDateReceiveEnd";
            valReceiveEnd.ControlToValidate = "txtDateReceiveEnd";
            valReceiveEnd.SetFocusOnError = true;
            valReceiveEnd.Display = ValidatorDisplay.Dynamic;
            valReceiveEnd.ErrorMessage = "* กรุณาระบุวันที่สิ้นสุดจำหน่ายเอกสารให้ถูกต้อง *";
            valReceiveEnd.ClientValidationFunction = "validateDate";
            panelValReceive.Controls.Add(valReceiveEnd);
            CustomValidator valBuild = new CustomValidator();
            valBuild.ID = "ValtxtDateBuild";
            valBuild.ControlToValidate = "txtDateBuild";
            valBuild.SetFocusOnError = true;
            valBuild.Display = ValidatorDisplay.Dynamic;
            valBuild.ErrorMessage = "* กรุณาระบุวันที่ดูสถานที่ให้ถูกต้อง *";
            valBuild.ClientValidationFunction = "validateDate";
            panelValBuild.Controls.Add(valBuild);
            CustomValidator valExplain = new CustomValidator();
            valExplain.ID = "ValtxtDateExplain";
            valExplain.ControlToValidate = "txtDateExplain";
            valExplain.SetFocusOnError = true;
            valExplain.Display = ValidatorDisplay.Dynamic;
            valExplain.ErrorMessage = "* กรุณาระบุวันที่ชี้แจงรายละเอียดให้ถูกต้อง *";
            valExplain.ClientValidationFunction = "validateDate";
            panelValExplain.Controls.Add(valExplain);
            CustomValidator valOfferStart = new CustomValidator();
            valOfferStart.ID = "ValtxtDateOfferStart";
            valOfferStart.ControlToValidate = "txtDateOfferStart";
            valOfferStart.SetFocusOnError = true;
            valOfferStart.Display = ValidatorDisplay.Dynamic;
            valOfferStart.ErrorMessage = "* กรุณาระบุวันที่เริ่มยื่นซองให้ถูกต้อง *";
            valOfferStart.ClientValidationFunction = "validateDate";
            panelValOffer.Controls.Add(valOfferStart);
            CustomValidator valOfferEnd = new CustomValidator();
            valOfferEnd.ID = "ValtxtDateOfferEnd";
            valOfferEnd.ControlToValidate = "txtDateOfferEnd";
            valOfferEnd.SetFocusOnError = true;
            valOfferEnd.Display = ValidatorDisplay.Dynamic;
            valOfferEnd.ErrorMessage = "* กรุณาระบุวันที่สิ้นสุดยื่นซองให้ถูกต้อง *";
            valOfferEnd.ClientValidationFunction = "validateDate";
            panelValOffer.Controls.Add(valOfferEnd);
            CustomValidator valDisclose = new CustomValidator();
            valDisclose.ID = "ValtxtDateDisclose";
            valDisclose.ControlToValidate = "txtDateDisclose";
            valDisclose.SetFocusOnError = true;
            valDisclose.Display = ValidatorDisplay.Dynamic;
            valDisclose.ErrorMessage = "* กรุณาระบุวันที่เปิดซอง/เสนอาคาให้ถูกต้อง *";
            valDisclose.ClientValidationFunction = "validateDate";
            panelValDisclose.Controls.Add(valDisclose);
        }

        #endregion

        #region tab คณะกรรมการ

        protected void LoadGridCommittee()
        {
            IList<PurchaseRequestCommitteeInfo> infoListCommittee = new List<PurchaseRequestCommitteeInfo>();
            if (ViewState["Committee"] != null)
            {
                infoListCommittee = (List<PurchaseRequestCommitteeInfo>)ViewState["Committee"];
            }
            else
            {
                int seq = GetSeq();
                infoListCommittee = bllPrCommittee.GetPurchaseRequestCommitteeFromBid(seq); ;
                ViewState["Committee"] = infoListCommittee;
            }
            Grid_Committee.DataSource = infoListCommittee;
            GridGroupByExpression geFunction = new GridGroupByExpression(Grid_Committee.Columns[2]);
            GridGroupByExpression geRefNo = new GridGroupByExpression(Grid_Committee.Columns[3]);
            Grid_Committee.MasterTableView.GroupByExpressions.Add(geFunction);
            Grid_Committee.MasterTableView.GroupByExpressions.Add(geRefNo);
            Grid_Committee.DataBind();

            cmdFac.GridCommand(panelList_Committee, panelGrid_Committee, panelCommand_Committee);
        }

        protected void LoadCommitteeFunction()
        {
            IList<MasterCommitteeFunctionInfo> infoList = bllComFunction.GetMasterCommitteeFunction();
            cbCommitteeFunction.DataSource = infoList;
            cbCommitteeFunction.DataBind();
        }

        protected void LoadCommitteePosition()
        {
            IList<MasterCommitteePositionInfo> infoList = bllComPosition.GetMasterCommitteePosition();
            cbCommitteePosition.DataSource = infoList;
            cbCommitteePosition.DataBind();
        }

        protected void Grid_Committee_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridCommittee();
        }

        protected void Grid_Committee_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                GridDataItem dataBoundItem = e.Item as GridDataItem;
                Image image = (Image)dataBoundItem["Image"].FindControl("Image1");
                if (dataBoundItem["InfoRecord.InfoStatus.Status"].Text == "W")
                {
                    image.ImageUrl = "../Image/Grid/Update.gif";
                }
                else
                {
                    image.ImageUrl = "../Image/Grid/Cancel.gif";
                }
            }
        }

        protected void rblCommitteeType_SelectedIndexChanged(object sender, EventArgs e)
        {
            panelInternal.Visible = (rblCommitteeType.SelectedValue == "1");
            panelExternal.Visible = (rblCommitteeType.SelectedValue == "2");
            LoadValidationCommittee();
        }

        protected void cbCommitteeInternalName_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            IList<HrmEmployeeInfo> infoList = bllEmployee.GetHrmEmployee(e.Text);
            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + ItemsPerRequest, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cbCommitteeInternalName.Items.Add(new RadComboBoxItem(infoList[i].Name, infoList[i].Seq.ToString()));
                TableRow tr = new TableRow();
                TableCell tdJobSite = new TableCell();
                Label lblJobSite = new Label();
                lblJobSite.Text = infoList[i].InfoJobSite.Name;
                tdJobSite.Width = Unit.Pixel(200);
                tdJobSite.Controls.Add(lblJobSite);
                tr.Cells.Add(tdJobSite);
                TableCell tdName = new TableCell();
                Label lblName = new Label();
                lblName.Text = infoList[i].Name;
                tdName.Width = Unit.Pixel(150);
                tdName.Controls.Add(lblName);
                tr.Cells.Add(tdName);
                TableCell tdPosition = new TableCell();
                Label lblPosition = new Label();
                lblPosition.Text = infoList[i].InfoPosition.Name;
                tdPosition.Width = Unit.Pixel(150);
                tdPosition.Controls.Add(lblPosition);
                tr.Cells.Add(tdPosition);
                TableCell tdClass = new TableCell();
                Label lblClass = new Label();
                lblClass.Text = infoList[i].InfoClass.Name;
                tdClass.Width = Unit.Pixel(190);
                tdClass.Controls.Add(lblClass);
                tr.Cells.Add(tdClass);
                ((Table)cbCommitteeInternalName.Items[j].FindControl("tableCommmitteeInternalName")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }

        private static string GetStatusMessage(int offset, int total)
        {
            if (total <= 0)
                return "ไม่มีข้อมูล";

            return String.Format("รายการที่ <b>1</b>-<b>{0}</b> จากทั้งหมด <b>{1}</b> รายการ", offset, total);
        }

        protected void OnAjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            RadAjaxPanel1.Controls.Add(Page.LoadControl("../UserControl/TIP_Bid_Committee_History.ascx"));
        }

        protected void AddNew_Committee_Click(object sender, EventArgs e)
        {
            cmdFac.AddNewCommand(panelList_Committee, panelGrid_Committee, panelCommand_Committee);
            LoadValidationCommittee();
        }

        protected void btnDelete_Committee_Click(object sender, EventArgs e)
        {
            IList<PurchaseRequestCommitteeInfo> infoListCommittee = new List<PurchaseRequestCommitteeInfo>();
            if (ViewState["Committee"] != null)
            {
                infoListCommittee = (List<PurchaseRequestCommitteeInfo>)ViewState["Committee"];
            }
            int[] data_value = new int[Grid_Committee.MasterTableView.GetSelectedItems().Length];
            int item = Grid_Committee.MasterTableView.GetSelectedItems().Length;
            foreach (GridDataItem data in Grid_Committee.MasterTableView.GetSelectedItems())
            {
                item = item - 1;
                data_value[item] = data.ItemIndex;
            }

            for (int i = 0; i < data_value.Length; i++)
            {
                infoListCommittee[data_value[i]].DeleteReason = txtDeleteReason.Text;
                infoListCommittee[data_value[i]].InfoRecord.InfoStatus.Status = SystemInfo._DeleteRecordStatus;
                infoListCommittee[data_value[i]].InfoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                infoListCommittee[data_value[i]].InfoRecord.Updated_when = DateTime.Now;
            }

            ViewState["Committee"] = infoListCommittee;
            LoadGridCommittee();
        }

        protected void Delete_Committee_Click(object sender, EventArgs e)
        {
            int[] data_value = new int[Grid_Committee.MasterTableView.GetSelectedItems().Length];
            int item = Grid_Committee.MasterTableView.GetSelectedItems().Length;
            foreach (GridDataItem data in Grid_Committee.MasterTableView.GetSelectedItems())
            {
                item = item - 1;
                data_value[item] = data.ItemIndex;
            }

            for (int i = 0; i < data_value.Length; i++)
            {
                ((List<PurchaseRequestCommitteeInfo>)ViewState["Committee"]).RemoveAt(data_value[i]);
            }

            LoadGridCommittee();
        }

        protected void AddNewSave_Committee_Click(object sender, EventArgs e)
        {
            IList<PurchaseRequestCommitteeInfo> infoListCommittee = new List<PurchaseRequestCommitteeInfo>();
            if (ViewState["Committee"] != null)
            {
                infoListCommittee = (List<PurchaseRequestCommitteeInfo>)ViewState["Committee"];
            }

            PurchaseRequestCommitteeInfo info = new PurchaseRequestCommitteeInfo();
            HrmEmployeeInfo infoEmployee = new HrmEmployeeInfo();
            MasterCommitteePositionInfo infoPosition = new MasterCommitteePositionInfo();
            MasterCommitteeFunctionInfo infoFunction = new MasterCommitteeFunctionInfo();
            HrmEmployeeInfo infoEmployeeDetail = new HrmEmployeeInfo();
            SysCommitteeTypeInfo infoType = new SysCommitteeTypeInfo();
            RecordInfo infoRecord = new RecordInfo();
            SysRecordStatusInfo infoStatus = new SysRecordStatusInfo();

            info.Ref_no = Convert.ToInt32(txtCommitteeRefno.Value);
            infoType.Seq = Convert.ToInt32(rblCommitteeType.SelectedValue);
            infoType.Name = (rblCommitteeType.SelectedItem.Text);
            infoPosition.Seq = Convert.ToInt32(cbCommitteePosition.SelectedValue);
            infoPosition.Name = cbCommitteePosition.SelectedItem.Text;
            infoFunction.Seq = Convert.ToInt32(cbCommitteeFunction.SelectedValue);
            infoFunction.Name = cbCommitteeFunction.SelectedItem.Text;
            if (infoType.Seq == 1) //เป็นบุคลากรภายใน
            {
                infoEmployee.Seq = Convert.ToInt32(cbCommitteeInternalName.SelectedValue);
                infoEmployee.Name = cbCommitteeInternalName.Text;
                infoEmployeeDetail = bllEmployee.GetHrmEmployee(Convert.ToInt32(infoEmployee.Seq));
                info.Name = infoEmployee.Name;
                info.Descr = (infoEmployeeDetail.InfoJobSite.Name.Length > 0 ? " <b>หน่วยงาน : </b>" + infoEmployeeDetail.InfoJobSite.Name : "")
                    + (infoEmployeeDetail.InfoPosition.Name.Length > 0 ? " <b>ตำแหน่ง :</b>" + infoEmployeeDetail.InfoPosition.Name : "")
                    + (infoEmployeeDetail.InfoClass.Name.Length > 0 ? " <b>ระดับ :</b>" + infoEmployeeDetail.InfoClass.Name : "");
            }
            else
            {
                info.Ex_name = txtCommitteeExternalName.Text;
                info.Ex_descr = txtCommitteeExternalDescr.Text;
                info.Name = info.Ex_name;
                info.Descr = info.Ex_descr;
            }
            infoStatus.Status = SystemInfo._WorkRecordStatus;
            infoRecord.Created_by = cn.UserID;
            infoRecord.Created_when = DateTime.Now;
            info.InfoType = infoType;
            info.InfoExployee = infoEmployee;
            info.InfoPosition = infoPosition;
            info.InfoFunction = infoFunction;
            infoRecord.InfoStatus = infoStatus;
            info.InfoRecord = infoRecord;
            infoListCommittee.Add(info);
            ResetCommittee();
            ViewState["Committee"] = infoListCommittee;
            LoadGridCommittee();
        }

        protected void ResetCommittee()
        {
            txtCommitteeRefno.Text = "";
            cbCommitteeInternalName.ClearSelection();
            cbCommitteeInternalName.Text = "";
            txtCommitteeExternalName.Text = "";
            txtCommitteeExternalDescr.Text = "";
            cbCommitteePosition.ClearSelection();
            cbCommitteePosition.Text = "";
            cbCommitteeFunction.ClearSelection();
            cbCommitteeFunction.Text = "";
        }

        protected void ShowGrid_Committee_Click(object sender, EventArgs e)
        {
            cmdFac.GridCommand(panelList_Committee, panelGrid_Committee, panelCommand_Committee);
        }

        protected void LoadValidationCommittee()
        {
            RequiredFieldValidator valCommitteeRefno = new RequiredFieldValidator();
            valCommitteeRefno.ID = "ValtxtCommitteeRefno";
            valCommitteeRefno.ControlToValidate = "txtCommitteeRefno";
            valCommitteeRefno.SetFocusOnError = true;
            valCommitteeRefno.Display = ValidatorDisplay.Dynamic;
            valCommitteeRefno.ErrorMessage = "* กรุณาระบุชุดที่ *";
            panelValtxtCommitteeRefno.Controls.Add(valCommitteeRefno);
            RequiredFieldValidator valCommitteeInternalName = new RequiredFieldValidator();
            valCommitteeInternalName.ID = "ValcbCommitteeInternalName";
            valCommitteeInternalName.ControlToValidate = "cbCommitteeInternalName";
            valCommitteeInternalName.SetFocusOnError = true;
            valCommitteeInternalName.Display = ValidatorDisplay.Dynamic;
            valCommitteeInternalName.ErrorMessage = "* กรุณาระบุชื่อกรรมการ *";
            panelValcbCommitteeInternalName.Controls.Add(valCommitteeInternalName);
            RequiredFieldValidator valCommitteeExternalName = new RequiredFieldValidator();
            valCommitteeExternalName.ID = "ValtxtCommitteeExternalName";
            valCommitteeExternalName.ControlToValidate = "txtCommitteeExternalName";
            valCommitteeExternalName.SetFocusOnError = true;
            valCommitteeExternalName.Display = ValidatorDisplay.Dynamic;
            valCommitteeExternalName.ErrorMessage = "* กรุณาระบุชื่อกรรมการ *";
            panelValtxtCommitteeExternalName.Controls.Add(valCommitteeExternalName);
            RequiredFieldValidator valCommitteePosition = new RequiredFieldValidator();
            valCommitteePosition.ID = "ValcbCommitteePosition";
            valCommitteePosition.ControlToValidate = "cbCommitteePosition";
            valCommitteePosition.SetFocusOnError = true;
            valCommitteePosition.Display = ValidatorDisplay.Dynamic;
            valCommitteePosition.ErrorMessage = "* กรุณาระบุตำแหน่งกรรมการ *";
            panelValcbCommitteePosition.Controls.Add(valCommitteePosition);
            RequiredFieldValidator valCommitteeFunction = new RequiredFieldValidator();
            valCommitteeFunction.ID = "ValcbCommitteeFunction";
            valCommitteeFunction.ControlToValidate = "cbCommitteeFunction";
            valCommitteeFunction.SetFocusOnError = true;
            valCommitteeFunction.Display = ValidatorDisplay.Dynamic;
            valCommitteeFunction.ErrorMessage = "* กรุณาระบุหน้าที่กรรมการ *";
            panelValcbCommitteeFunction.Controls.Add(valCommitteeFunction);
            //RequiredFieldValidator valDelete = new RequiredFieldValidator();
            //valDelete.ID = "ValtxtDeleteReason";
            //valDelete.ControlToValidate = "txtDeleteReason";
            //valDelete.SetFocusOnError = true;
            //valDelete.Display = ValidatorDisplay.Dynamic;
            //valDelete.ErrorMessage = "* กรุณาระบุสาเหตุที่คัดออก *";
            //valDelete.ValidationGroup = "ValDelete";
            //panelValtxtDeleteReason.Controls.Add(valDelete);
        }

        protected void backButton_Committee_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('Detail',1, 'validate');");
            LoadValiDateDetail();
        }

        protected void nextButton_Committee_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('File',3, 'validate');");
        }

        #endregion

        #region tab เอกสารแนบ

        protected void LoadGridFile()
        {
            IList<DocumentInfo> infoListFile = new List<DocumentInfo>();
            if (ViewState["File"] != null)
            {
                infoListFile = (List<DocumentInfo>)ViewState["File"];
            }
            Grid_File.DataSource = infoListFile;
            Grid_File.DataBind();

            cmdFac.GridCommand(panelList_File, panelGrid_File, panelCommand_File);
        }

        protected void ShowGrid_File_Click(object sender, EventArgs e)
        {
            LoadGridFile();
        }

        protected void AddNew_File_Click(object sender, EventArgs e)
        {
            cmdFac.AddNewCommand(panelList_File, panelGrid_File, panelCommand_File);
            LoadValidateFile();
        }

        private void LoadValidateFile()
        {
            RequiredFieldValidator valFileName = new RequiredFieldValidator();
            valFileName.ID = "ValtxtFileName";
            valFileName.ControlToValidate = "txtFileName";
            valFileName.SetFocusOnError = true;
            valFileName.Display = ValidatorDisplay.Dynamic;
            valFileName.ErrorMessage = "* กรุณาระบุชื่อไฟล์ *";
            panelValtxtFileName.Controls.Add(valFileName);
            RequiredFieldValidator valAttachment = new RequiredFieldValidator();
            valAttachment.ID = "Valattachment";
            valAttachment.ControlToValidate = "attachment";
            valAttachment.SetFocusOnError = true;
            valAttachment.Display = ValidatorDisplay.Dynamic;
            valAttachment.ErrorMessage = "* กรุณาระบุที่อยู่ไฟล์ *";
            panelValattachment.Controls.Add(valAttachment);
        }

        protected void AddNewSave_File_Click(object sender, EventArgs e)
        {
            IList<DocumentInfo> infoListFile = new List<DocumentInfo>();
            FileInfo infoFile = new FileInfo(hdSourceFile.Value);
            DocumentInfo info = new DocumentInfo();
            RecordInfo infoRecord = new RecordInfo();
            if (ViewState["File"] != null)
            {
                infoListFile = (List<DocumentInfo>)ViewState["File"];
            }
            infoRecord.Created_by = cn.UserID;
            infoRecord.Created_when = DateTime.Now;
            info.File_info = infoFile;
            info.Name = txtFileName.Text;
            info.Dest_path = hdSourceFile.Value;
            info.InfoRecord = infoRecord;
            infoListFile.Add(info);
            ViewState["File"] = infoListFile;
            LoadGridFile();
        }

        protected void Delete_File_Click(object sender, EventArgs e)
        {
            int[] data_value = new int[Grid_File.MasterTableView.GetSelectedItems().Length];
            int item = Grid_File.MasterTableView.GetSelectedItems().Length;
            foreach (GridDataItem data in Grid_File.MasterTableView.GetSelectedItems())
            {
                item = item - 1;
                data_value[item] = data.ItemIndex;
            }

            for (int i = 0; i < data_value.Length; i++)
            {
                ((List<DocumentInfo>)ViewState["File"]).RemoveAt(data_value[i]);
            }

            LoadGridFile();
        }

        protected void Grid_File_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridFile();
        }

        protected void backButton_File_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('Committee',2, 'validate');");
        }

        protected void finishButton_File_Click(object sender, EventArgs e)
        {
            BidInfo info = new BidInfo();
            PurchaseRequestInfo infoPr = new PurchaseRequestInfo();
            HrmEmployeeInfo infoEmployee = new HrmEmployeeInfo();
            HrmJobSiteInfo infoJobSite = new HrmJobSiteInfo();
            SysYearTypeInfo infoYearType = new SysYearTypeInfo();
            RecordInfo infoRecord = new RecordInfo();
            IList<PurchaseRequestCommitteeInfo> infoListCommittee = new List<PurchaseRequestCommitteeInfo>();
            IList<DocumentInfo> infoListFile = new List<DocumentInfo>();

            if (ViewState["Committee"] != null)
            {
                infoListCommittee = (List<PurchaseRequestCommitteeInfo>)ViewState["Committee"];
            }
            if (ViewState["File"] != null)
            {
                infoListFile = (List<DocumentInfo>)ViewState["File"];
            }

            infoYearType.Seq = Convert.ToInt32(hdYearType.Value);
            info.Year = Convert.ToInt32(lblBgmYear.Text);
            info.Ref_no = txtRefNo.Text;
            info.Name = txtName.Text;
            infoPr.Seq = GetSeq();
            info.DateBid = Convert.ToDateTime(txtDate.TextWithLiterals);
            infoEmployee.Seq = 1;
            string[] strJobSite = GetUserJobSite(Convert.ToInt32(infoEmployee.Seq));
            infoJobSite.Seq = Convert.ToInt32(strJobSite[0]);
            info.DateAnnounce = (txtDateAnnounce.Text.Length > 0 ? (Nullable<DateTime>)Convert.ToDateTime(txtDateAnnounce.TextWithLiterals) : null);
            info.DateStartReceive = (txtDateReceiveStart.Text.Length > 0 ? (Nullable<DateTime>)Convert.ToDateTime(txtDateReceiveStart.TextWithLiterals) : null);
            info.DateEndReceive = (txtDateReceiveEnd.Text.Length > 0 ? (Nullable<DateTime>)Convert.ToDateTime(txtDateReceiveEnd.TextWithLiterals) : null);
            info.DateBuilding = (txtDateBuild.Text.Length > 0 ? (Nullable<DateTime>)Convert.ToDateTime(txtDateBuild.TextWithLiterals) : null);
            info.DateExplain = (txtDateExplain.Text.Length > 0 ? (Nullable<DateTime>)Convert.ToDateTime(txtDateExplain.TextWithLiterals) : null);
            info.DateStartOffer = (txtDateOfferStart.Text.Length > 0 ? (Nullable<DateTime>)Convert.ToDateTime(txtDateOfferStart.TextWithLiterals) : null);
            info.DateEndOffer = (txtDateOfferEnd.Text.Length > 0 ? (Nullable<DateTime>)Convert.ToDateTime(txtDateOfferEnd.TextWithLiterals) : null);
            info.DateDisclose = (txtDateDisclose.Text.Length > 0 ? (Nullable<DateTime>)Convert.ToDateTime(txtDateDisclose.TextWithLiterals) : null);
            info.TimeStartReceive = (txtTimeReceiveStart.Text.Length > 0 ? (Nullable<TimeSpan>)TimeSpan.Parse(txtTimeReceiveStart.TextWithLiterals) : null);
            info.TimeEndReceive = (txtTimeReceiveEnd.Text.Length > 0 ? (Nullable<TimeSpan>)TimeSpan.Parse(txtTimeReceiveEnd.TextWithLiterals) : null);
            info.TimeStartBuilding = (txtTimeBuildStart.Text.Length > 0 ? (Nullable<TimeSpan>)TimeSpan.Parse(txtTimeBuildStart.TextWithLiterals) : null);
            info.TimeEndBuilding = (txtTimeBuildEnd.Text.Length > 0 ? (Nullable<TimeSpan>)TimeSpan.Parse(txtTimeBuildEnd.TextWithLiterals) : null);
            info.TimeExplain = (txtTimeExplain.Text.Length > 0 ? (Nullable<TimeSpan>)TimeSpan.Parse(txtTimeExplain.TextWithLiterals) : null);
            info.TimeStartOffer = (txtTimeOfferStart.Text.Length > 0 ? (Nullable<TimeSpan>)TimeSpan.Parse(txtTimeOfferStart.TextWithLiterals) : null);
            info.TimeEndOffer = (txtTimeOfferEnd.Text.Length > 0 ? (Nullable<TimeSpan>)TimeSpan.Parse(txtTimeOfferEnd.TextWithLiterals) : null);
            info.TimeDisclose = (txtTimeDisclose.Text.Length > 0 ? (Nullable<TimeSpan>)TimeSpan.Parse(txtTimeDisclose.TextWithLiterals) : null);
            info.PlaceReceive = txtPlaceReceive.Text;
            info.PlaceOffer = txtPlaceOffer.Text;
            info.ReceiveType = (rdbFree.Checked ? "F" : "S");
            info.DocumentAmount = (info.ReceiveType == "S" ? (Nullable<int>)Convert.ToInt32(txtDocAmount.Value.ToString()) : null);
            infoRecord.Created_by = cn.UserID;
            infoRecord.Created_when = DateTime.Now;

            info.InfoRecord = infoRecord;
            info.InfoPr = infoPr;
            info.InfoEmployeeBid = infoEmployee;
            info.InfoJobSiteBid = infoJobSite;
            info.InfoYearType = infoYearType;

            try
            {
                bllBid.Insert(info, infoListCommittee, infoListFile);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }

            RadManager1.Alert(SystemInfo._InsertComplete);
            RadManager1.ResponseScripts.Add(@"CloseWindow();");
        }

        protected void OnAjaxRequestFile(object sender, AjaxRequestEventArgs e)
        {
            RadAjaxPanel2.Controls.Add(Page.LoadControl("../UserControl/TIP_Bid_File_History.ascx"));
        }

        private string[] GetUserJobSite(int emp_seq)
        {
            return bllPersonal.GetUserJobSite(emp_seq);
        }

        #endregion
    }
}
